// #include<iostream>
// #include<stdio.h>
// #include<unistd.h>

// int main()
// {
//     int pipefd[2] = { 0 };
//     int n = pipe(pipefd);
//     if(n == 0)
//     {
//         printf("pipefd[0]:%d, pipefd[1]:%d\n", pipefd[0], pipefd[1]);
//     }

//     return 0;
// }


#include<iostream>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<string>
#include<sys/wait.h>

int main()
{
    int pipefd[2] = { 0 };
    int n = pipe(pipefd);
    if(n < 0)
    {
        perror("pipe");
        return 0;
    }
    pid_t pid = fork();
    if(pid < 0)
    {
        perror("fork");
        exit(1);
    }
    else if(pid == 0)
    {
        // 子进程
        close(pipefd[0]);
        std::string str = "我是子进程";
        std::string self = std::to_string(getpid());
        int count = 1;
        while(1)
        {
            std::string message = str + ", " + self + ", " + std::to_string(count++);
            write(pipefd[1], message.c_str(), message.size());        
            sleep(1);
        }
    }
    else
    {
        // 父进程
        close(pipefd[1]);
        while(1)
        {
            char buff[1024] = { 0 };
            ssize_t n = read(pipefd[0], buff, sizeof(buff) - 1);
            if(n > 0)
            {
                buff[n] = '\0';
                std::cout << "父进程收到消息->" << buff << std::endl;
            }
        }
        int ret_pid = waitpid(pid, nullptr, 0);
    }

    return 0;
}